﻿using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel;
using PSE.Updater.Common;
using PSE.Updater.Common.Gateway.DataContract;
using PSE.Updater.Common.Gateway.ServiceContract;
using PSE.Updater.Common.Providers;
using PSE.Updater.Common.Providers.Interfaces;
using PSE.Framework.ErrorLogging;

namespace PSE.Updater.Server.Service
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class UpdatesDiscoveryService : IUpdatesDiscoveryService
    {
        /// <summary>
        /// Recuperar a lista de atualizacoes disponiveis para uma lista de modulos informada
        /// </summary>
        /// <param name="moduleVersions">Módulos e suas versões</param>
        /// <returns>Lista de atualizações disponíveis</returns>
        public List<ModuleUpdatePackage> GetAvailableUpdates(ProviderType type, List<ModuleVersion> moduleVersions)
        {
            if (moduleVersions == null)
                throw new FaultException(new FaultReason("Ao menos um módulo deve ser informado"), new FaultCode("ArgumentNull"));

            try
            {
                DebugLog.Write("Recuperando a lista de atualizacoes disponiveis para uma lista de modulos informada");

                IList<IFileDetails> allPackages = Engine.UpdateService.Instance.GetAvailableUpdates(type, moduleVersions);
                return ConvertToModuleUpdatePackageList(allPackages);
            }
            catch (Exception ex)
            {
                ErrorLogger.WriteLog(LogType.Error, ex);
                throw new FaultException(new FaultReason(ex.ToString()), new FaultCode(ex.Message));
            }
        }

        private List<ModuleUpdatePackage> ConvertToModuleUpdatePackageList(IList<IFileDetails> packageDetails)
        {
            if (packageDetails == null)
                return null;
            else
            {
                List<ModuleUpdatePackage> ret = new List<ModuleUpdatePackage>();
                foreach (IFileDetails pd in packageDetails)
                {
                    ret.Add(new ModuleUpdatePackage()
                    {
                        ModuleName = pd.ModuleName,
                        SystemName = pd.SystemName,
                        Status = pd.Status,
                        UpdateDescription = pd.UpdateDescription,
                        Version = pd.Version.ToString(),
                        PackageSize = pd.Size,
                        //FileName = string.IsNullOrEmpty(pd.FilePath) ? string.Empty : Path.GetFileName(pd.FilePath)
                        FileName = pd.FilePath
                        //Type = pd.Type
                    });
                }
                return ret;
            }
        }
    }
}